package cn.jy.careuplusdoctor.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.text.TextUtils;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

//实现图片缓存类
public class BitmapLruCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {
	public BitmapLruCache(int maxSize) {
		super(maxSize);
	}

	@Override
	protected int sizeOf(String key, Bitmap bitmap) {
		return bitmap.getRowBytes() * bitmap.getHeight();
	}

	@Override
	public Bitmap getBitmap(String url) {
		return get(url);
	}

	@Override
	public void putBitmap(String url, Bitmap bitmap) {
		put(url, bitmap);
	}

	private static ImageLoader imageLoader;

	public static ImageLoader getImageLoader(Context context) {
		if (imageLoader == null) {
			RequestQueue mRequestQueue = Volley.newRequestQueue(context);

			int cacheSize = 1024 * 1024 * 2;
			imageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
		}
		return imageLoader;
	}

	/**
	 * 用于校验服务器发来的图片url
	 * @param url 图片url地址
	 * @return 正常url返回传进来的url, 非法url返回一个默认的正常url
	 */
	public static String checkImgUrl(String url,String defaultUrl) {
		String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
		Pattern patt = Pattern.compile(regex);
		Matcher matcher = patt.matcher(url);
		boolean isMatch = matcher.matches();
		if (TextUtils.isEmpty(url) || !isMatch) {
			return defaultUrl;
		} else {
			return url;
		}
	}
	
	/**
	 * 用于校验服务器发来的图片url
	 * @param url 图片url地址
	 * @return 正常url返回传进来的url, 非法url返回一个默认的正常url
	 */
	public static String checkImgUrl(String url) {
		return checkImgUrl(url,"");
	}
}
